package com.ulwx.database.dbpool;

import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.ulwx.database.DataBase;

public class CheckSlaveThread extends Thread {

	public static int SleepTime = 60 * 1; // 秒
	private static Logger log = Logger.getLogger(CheckSlaveThread.class);
	private volatile boolean stop = false;
	private String poolName = "";
	private String slaveServerName = "";
	private DataSource ds;
	private volatile boolean isRealStop = false;

	public static int getSleepTime() {
		return SleepTime;
	}

	public static void setSleepTime(int sleepTime) {
		SleepTime = sleepTime;
	}

	public boolean isRealStop() {
		return isRealStop;
	}

	public CheckSlaveThread(String poolName, String slaveServerName,
			DataSource ds) {
		this.poolName = poolName;
		this.slaveServerName = slaveServerName;
		this.ds = ds;
	}

	public synchronized void stopThread() {
		this.stop = true;
		this.interrupt();

	}

	public void run() {
		// TODO Auto-generated method stub
		// System.out.println("1");
		try {
			Thread.sleep(1000 * 15);
		} catch (Exception e) {
			log.info("监控线程被中断！");
		}
		while (true && !Thread.currentThread().isInterrupted() && !this.stop) {

			// System.out.println("2");
			boolean res = DBPoolFactory.startDataSource(ds);
			if (!res) {
				DBPoolFactory.getInstance().setSlaveExceptionTime(this.poolName,
						this.slaveServerName);
			}
			try {
				// System.out.println("4");
				TimeUnit.SECONDS.sleep(SleepTime);// 沉睡5分钟
			} catch (Exception e) {
				log.debug("stop!!!");
				isRealStop = true;
				// System.out.println("5");
				return;
			}

		}
		isRealStop = true;
		log.debug("stop!");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		CheckSlaveThread c1 = new CheckSlaveThread("", "", null);
		CheckSlaveThread c2 = new CheckSlaveThread("", "", null);
		CheckSlaveThread c3 = new CheckSlaveThread("", "", null);
		// c1.start();
		// c2.start();

		c3.start();
		Thread.sleep(1000);
		c3.stopThread();
		// Thread.sleep(5345);
	}

}
